<template>
  <a-drawer
    v-model:open="visible"
    :width="800"
    @close="onClose"
    title=""
		:closable='false'
  >
    <div class="task-drawer-content">
      <div class="task-drawer-left">
        <h2 class="task-title">{{ taskData.title }}</h2>

        <div class="task-info">
          <!-- 任务发布时间：<span class='time'>{{formatDateTime(taskData.releaseTime) }}</span> -->
          {{ t('modal','任务截止时间') }}:<span class='time'>{{ formatDateTime(taskData.expiredTime) }}</span>
					<!-- <span>任务于<span class='time'>{{formatDateTime(taskData.releaseTime) }}</span>发布，于<span class='time'>{{ formatDateTime(taskData.expiredTime) }}</span>截止</span> -->
        </div>

        <div class="task-description">
          <h3>{{ t('taskDetail',"任务描述") }}</h3>
					<a-textarea
					  v-model:value="taskData.describe"
						:autosize='{ minRows: 2, maxRows: 100 }'
					  :disabled="true"
					  :class="disabled"
						
					/>
        </div>

        <div class="task-answer">
          <a-textarea
            v-model:value="taskData.submitContent"
						:autosize='{ minRows: 2, maxRows: 8 }'
            :disabled="taskData.status === 3"
            :class="{ disabled: taskData.status === 3}"
						:placeholder="t('taskDetail','请在这里作答')"
          />
        </div>

        
        <!-- <div class="task-description" v-if="taskData.scoreDetail&&taskData.scoreDetail!=null">
          <h3>得分原因</h3>
					<a-textarea
					  v-model:value="taskData.scoreDetail"
						:autosize='{ minRows: 2, maxRows: 100 }'
					  :disabled="true"
					  :class="disabled"
						
					/>
        </div> -->

        <div
          class="task-attachments"
          :class="{ disabled: taskData.status === 3 }"
        >
          <h3>{{ t('taskDetail','附件上传') }}</h3>
          <a-upload
            :disabled="taskData.status === 3"
            :file-list="fileList"
            @change="handleFileChange"
            :beforeUpload="beforeUpload"
            @remove="handleFileRemove"
          >
            <a-button :disabled="taskData.status === 3" >{{ t('taskDetail','上传文件') }}</a-button>
          </a-upload>
        </div>
				
      </div>

      <div class="task-drawer-right">
        <div class="info-item">
          <span class="label">{{ t('taskDetail','任务类型') }}：</span>
          <span class="value">{{ {0: t('control','项目任务'),1:t('control','学习任务')}[taskData.type]||t('common','暂无') }}</span>
        </div>
        <div class="info-item">
          <span class="label">{{ t('control','任务状态') }}：</span>
          <span class="value" :class="getStatusClass(taskData.status)">
            {{ getStatusText(taskData.status)||t('common','暂无') }}
          </span>
        </div>
       <!-- <div class="info-item">
          <span class="label">归属项目：</span>
          <span class="value">{{ taskData.project }}</span>
        </div> -->
        <div class="info-item">
          <span class="label">{{ t('modal','任务分值') }}：</span>
          <span class="value">{{ taskData.scoreSetting||t('common','暂无') }}</span>
        </div>
        <div class="info-item">
          <span class="label">{{ t('taskDetail','任务得分') }}：</span>
          <span class="value">{{ taskData.score||t('common','暂无') }}</span>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="task-drawer-footer">
        <a-space>
          <a-button
            type="primary"
            @click="submitTask"
            :disabled="taskData.status === 3 || submitting"
          >
            {{ t('control','提交') }}
          </a-button>
          <!-- <a-button @click="saveTask" :disabled="taskData.status === 3">
            保存
          </a-button> -->
          <a-button @click="onClose">{{ t('control','取消') }}</a-button>
        </a-space>
      </div>
    </template>
  </a-drawer>
</template>

<script setup>
import { ref, defineProps, defineEmits, toRefs, watch } from "vue";
import {formatDateTime} from '@/utils.js'
import {studentSubmitTask,studentDeleteFile} from '@/request/process/processTask.js'
import { message } from 'ant-design-vue';
import { t } from '@/i18n'

defineOptions({
  name: "StudentTaskDetail",
});
const props = defineProps({
  visible: Boolean,
  taskData: {
    type: Object,
    default: () => ({}),
  },
});




let { visible, taskData } = toRefs(props);
const emit = defineEmits(["update:visible", "submit", "save"]);

const answer = ref("");
const fileList = ref([]);
const submitting = ref(false);

// 监听taskData变化,初始化fileList
watch(() => taskData.value, (newVal) => {
  if(newVal.files && newVal.files.length > 0) {
    fileList.value = newVal.files.map(file => ({
      uid: file.id,
      name: file.name,
      status: 'done',
      id: file.id,
      url: file.url
    }));
  } else {
    fileList.value = [];
  }
}, { immediate: true });

const getStatusText = (status) => {
  const statusMap = {
    1: t('control',"未完成"),
    2: t('control',"已完成"),
    3: t('control',"已得分"),
  };
  return statusMap[status] || t('control','未知状态');
};

const getStatusClass = (status) => {
  const statusClassMap = {
    1: "status-pending",
    2: "status-completed",
    3: "status-scored",
  };
  return statusClassMap[status] || "";
};

const onClose = () => {
  emit("update:visible", false);
};

const beforeUpload = (file) => {
  return false; // 阻止自动上传
};

const handleFileChange = (info) => {
  fileList.value = [...info.fileList];
};

const handleFileRemove = async (file) => {
  if (!file.id) {
    fileList.value = fileList.value.filter((item) => item.uid !== file.uid)
    return
  }
  try {
    const res = await studentDeleteFile(file.id);
    if (res) {
      message.success(t('common','删除成功'));
      taskData.value.files = taskData.value.files.filter(item => item.id !== file.id);
      fileList.value = fileList.value.filter(item => item.id !== file.id);
    }
  } catch (error) {
    message.error(t('common','删除失败'));
  }
};

const submitTask = async () => {
  if(submitting.value) return;
  
  console.log(taskData.value)
  console.log(taskData.value.submitContent?.trim())
  if (!taskData.value.submitContent?.trim()) {
    message.warning(t('common','请填写答案内容'));
    return;
  }

  try {
    submitting.value = true;
    const formData = new FormData();
    formData.append('description', taskData.value.submitContent);
    
    // 分别添加每个文件到 FormData
    if(fileList.value) {
      fileList.value.forEach((file) => {
        if (file.originFileObj) {
          formData.append('files', file.originFileObj);
        }
      });
    }
    
    const params = {
      id: taskData.value.id,
      data: formData
    };
    console.log('提交数据',params)
    const res = await studentSubmitTask(params);
    console.log('提交',res)
    if (res && res.code == 200) {
      message.success(t('common', '提交成功'));
    } else {
      message.error(t('common','提交失败'));
    }
    emit("update:visible", false);
    emit("submit");
  } catch (error) {
    message.error(t('common','提交失败'));
    console.error('提交失败:', error);
  } finally {
    submitting.value = false;
  }
};

const saveTask = () => {
  emit("save", {
    answer: answer.value,
    files: fileList.value,
  });
};
</script>

<style lang="scss" scoped>
.task-drawer {
  &-content {
		height:100%;
		width:100%;
		padding:0 15px;
    display: flex;
    gap: 24px;
		overflow: auto;
  }

  &-left {
    flex: 1;
		padding-right:24px;
		border-right: 1px solid #f0f0f0;
  }

  &-right {
    width: 240px;
    // padding-left: 24px;
    // border-left: 1px solid #f0f0f0;
  }

  &-footer {
    text-align: right;
    padding: 16px 24px;
  }
}

.task {
  &-title {
    font-size: 18px;
    font-weight: 700;
    margin-bottom: 16px;
		color:#575757;
  }

  &-info {
    margin: 16px 0;
		font-size: 14px;
    color: #6e6e6e;
    margin-left: 2px;

    .time {
      margin:0 5px;
			display: inline-block;
    }
  }

  &-description {
    margin: 20px 0 24px 0;

    h3 {
      margin-bottom: 12px;
			color: #3a3c4b;
			font-size: 14px;
			font-weight: 700;
			line-height: 24px;
    }
		:deep(.ant-input-disabled,.ant-input[disabled]){
			cursor:auto;
			color:#6e6e6e;
		}
		p{
			line-height: 24px;
		}
  }

  &-answer {
    margin: 24px 0;

    h3 {
      font-size: 16px;
      margin-bottom: 12px;
    }

    :deep(.ant-input) {
      &.disabled {
        background-color: #f5f5f5;
      }
    }
  }

  &-attachments {
    margin: 24px 0;

    h3 {
      margin-bottom: 12px;
			color: #3a3c4b;
			font-size: 14px;
			font-weight: 700;
			line-height: 24px;
    }

    &.disabled {
      opacity: 0.6;
    }
  }
}

.info-item {
  margin-bottom: 16px;

  .label {
    color: #666;
    display: inline-block;
    width: 80px;
  }

  .value {
    color: #333;
  }
}

.status {
  &-pending {
    color: #faad14;
  }

  &-completed {
    color: #52c41a;
  }

  &-scored {
    color: #1890ff;
  }
}
</style>
